<template>
  <div id="DoctorDetail">
    <!-- 麵包屑導航 -->
    <BreadcrumbComponent :breadcrumbItems="breadcrumbItems" />
    <a-space direction="vertical" style="width: 100%">
      <!-- 消息詳情卡片 -->
      <a-card title="醫師基礎信息" :loading="loading">
        <template v-if="!loading && !doctorInfo.id">
          <a-empty description="數據加載失敗，請重試" />
        </template>
        <template v-else>
          <a-descriptions
            bordered
            :column="{ xxl: 4, xl: 4, lg: 3, md: 3, sm: 2, xs: 1 }"
          >
            <a-descriptions-item label="醫師姓名">
              {{ doctorInfo.name }}
            </a-descriptions-item>
            <a-descriptions-item label="員工編號">
              {{ doctorInfo.staffCode }}
            </a-descriptions-item>
            <a-descriptions-item label="員工類型">
              <a-tag :color="doctorInfo.staffType === 2 ? 'blue' : 'green'">
                {{ doctorInfo.staffType === 2 ? "員工" : "合作" }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="當前駐診形式">
              <a-tag v-if="doctorInfo.currentShiftType == 1" color="#2db7f5"
                >全日</a-tag
              >
              <a-tag
                v-else-if="doctorInfo.currentShiftType == 2"
                color="#88e8db"
                >半日</a-tag
              >
              <a-tag v-else color="default">未知</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </template>
      </a-card>
      <a-divider>診金分成</a-divider>
      <a-card title="診金類型分成" :loading="loading">
        <a-tabs type="card">
          <a-tab-pane tab="當前方案" key="1">
            <a-empty :description="null" v-if="!consultPlanData.id" />
            <a-card v-else>
              <a-descriptions>
                <a-descriptions-item label="當前生效方案">{{
                  consultPlanData.title
                }}</a-descriptions-item>
                <a-descriptions-item label="開始日期">{{
                  consultPlanData.startDate
                }}</a-descriptions-item>
                <a-descriptions-item label="結束日期">{{
                  consultPlanData.endDate
                }}</a-descriptions-item>
              </a-descriptions>
              <a-divider />
              <a-descriptions title="默認">
                <a-descriptions-item>
                  <template #label>
                    {{ customConsultTypes.find((i) => i.key === 0)?.label }}
                  </template>
                  <span v-if="consultPlanData.items[0]?.shareType == 1">
                    $
                  </span>
                  {{ consultPlanData.items[0]?.shareValue }}
                  <span v-if="consultPlanData.items[0]?.shareType == 2">
                    %
                  </span>
                </a-descriptions-item>
              </a-descriptions>
              <a-divider />
              <a-descriptions title="自定 義">
                <a-descriptions-item
                  v-for="item in consultPlanData.items.slice(1)"
                  :key="item.consultType"
                >
                  <template #label>
                    {{
                      customConsultTypes?.find(
                        (i) => i.key === item.consultType
                      )?.label
                    }}
                  </template>
                  <span v-if="item.shareType == 1"> $ </span>
                  {{ item.shareValue }}
                  <span v-if="item.shareType == 2"> % </span>
                </a-descriptions-item>
              </a-descriptions>
            </a-card>
          </a-tab-pane>
          <a-tab-pane key="2">
            <template #tab>
              <span>
                <SettingOutlined />
                設置方案
              </span>
            </template>
            <a-card>
              <DoctorConsultPlanPage :doctorId="Number(route.params.id)" />
            </a-card>
          </a-tab-pane>
        </a-tabs>
      </a-card>

      <!-- 指定服務診金分成 -->
      <a-card title="指定服務診金分成" :loading="loading">
        <a-row :gutter="[16, 16]">
          <a-col :span="8" v-for="item in specifyServicesData" :key="item.type">
            <a-card brodered hoverable>
              <a-statistic
                :value="item.shareValue"
                :precision="2"
                :value-style="{ color: '#619ac3' }"
              >
                <template #prefix v-if="item.shareType == 1">$</template>
                <template #suffix v-if="item.shareType == 2">%</template>
                <template #title>
                  <a-typography-title :level="5">
                    {{ item.name }}
                  </a-typography-title>
                </template>
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
      </a-card>

      <a-divider>銷售分成</a-divider>

      <a-card title="附加項目分成" :loading="loading">
        <a-row :gutter="[16, 16]">
          <a-col
            :span="8"
            v-for="item in additonalShareRuleData"
            :key="item.type"
          >
            <a-card brodered hoverable>
              <a-statistic
                :value="item.shareValue"
                :precision="2"
                :value-style="{ color: '#619ac3' }"
              >
                <template #prefix v-if="item.shareType == 1">$</template>
                <template #suffix v-if="item.shareType == 2">%</template>
                <template #title>
                  <a-typography-title :level="5">
                    <template v-if="item.type === 1"> 套票 </template>
                    <template v-else-if="item.type === 2"> 針灸 </template>
                    <template v-else-if="item.type === 3"> 天灸 </template>
                    <template v-else> 未知 </template>
                  </a-typography-title>
                </template>
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
      </a-card>

      <a-card title="常規銷售分成" :loading="loading">
        <a-descriptions :column="2">
          <a-descriptions-item label="規則名稱">
            <RouterLink
              :to="{
                name: 'RegularShareDetail',
                params: { id: regularShareRuleData.id },
              }"
            >
              {{ regularShareRuleData.name }}
            </RouterLink>
          </a-descriptions-item>
          <a-descriptions-item label="規則類型">
            <a-tag color="green" v-if="regularShareRuleData.ruleType === 1"
              >跳級</a-tag
            >
            <a-tag color="blue" v-else-if="regularShareRuleData.ruleType === 2"
              >累進</a-tag
            >
            <a-tag color="default" v-else>未知</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="開始日期">{{
            regularShareRuleData.validFrom
          }}</a-descriptions-item>
          <a-descriptions-item label="結束日期">{{
            regularShareRuleData.validTo
          }}</a-descriptions-item>
        </a-descriptions>
        <a-divider />
        <a-table
          :columns="
            getRegularTableColumns(Number(regularShareRuleData.ruleType))
          "
          :data-source="regularShareRuleData.items"
          :pagination="false"
          bordered
        >
        </a-table>
      </a-card>

      <a-card title="附加推廣分成" :loading="loading">
        <a-descriptions :column="2">
          <a-descriptions-item label="規則名稱">
            <RouterLink
              :to="{
                name: 'ExtraShareDetail',
                params: { id: extraShareRuleData.id },
              }"
            >
              {{ extraShareRuleData.name }}
            </RouterLink>
          </a-descriptions-item>
          <a-descriptions-item label="規則類型">
            <a-tag color="green" v-if="extraShareRuleData.ruleType === 1"
              >跳級</a-tag
            >
            <a-tag color="blue" v-else-if="extraShareRuleData.ruleType === 2"
              >累進</a-tag
            >
            <a-tag color="default" v-else>未知</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="開始日期">{{
            extraShareRuleData.validFrom
          }}</a-descriptions-item>
          <a-descriptions-item label="結束日期">{{
            extraShareRuleData.validTo
          }}</a-descriptions-item>
        </a-descriptions>
        <a-divider />
        <a-tabs>
          <a-tab-pane
            :key="index"
            :tab="extraTypes[index]"
            v-for="(items, index) in extraShareRuleData.items"
          >
            <a-table
              :columns="extraColumns"
              :dataSource="items"
              :pagination="false"
              bordered
            >
              <template #headerCell="{ column }">
                {{ column.title }}
              </template>
              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'shareRatio'">
                  <template v-if="record.shareType === 1"
                    >$ {{ record.shareRatio }}</template
                  >
                  <template v-else> {{ record.shareRatio }}%</template>
                </template>
                <template v-if="column.dataIndex === 'updatedAt'">
                  {{ $formatDate(record.updatedAt) }}
                </template>
              </template>
            </a-table>
          </a-tab-pane>
        </a-tabs>
      </a-card>

      <!-- 操作按鈕 -->
      <BackButton />
    </a-space>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { SettingOutlined } from "@ant-design/icons-vue";
import { useRoute } from "vue-router";
import { doctorApi } from "@/api";
import { useCustomConsultTypeStore } from "@/store/customConsultTypeStore";
import BreadcrumbComponent from "@/components/BreadcrumbComponent.vue";
import BackButton from "@/components/BackButton.vue";
import DoctorConsultPlanPage from "./components/DoctorConsultPlanPage.vue";
import { getRegularTableColumns, extraColumns } from "@/models/doctorShareRule";

const route = useRoute();
const customConsultTypeStore = useCustomConsultTypeStore();

// 麵包屑導航
const breadcrumbItems = [
  { url: "/doctor", name: "醫師列表" },
  { url: "", name: "醫師分成規則" },
];

// 詳情數據
const customConsultTypes = ref([]);
const loading = ref(false);

const doctorInfo = reactive({
  id: 0,
  name: "",
  staffCode: "",
  staffType: 2,
  currentShiftType: 1,
});
const consultPlanData = reactive({
  id: 0,
  title: "",
  startDate: "",
  endDate: "",
  items: [],
});
const specifyServicesData = ref<any>({});
const additonalShareRuleData = ref<any>({});
const regularShareRuleData = reactive({
  id: 0,
  name: "",
  ruleType: 1,
  validFrom: "",
  validTo: "",
  items: [],
});

const extraTypes = {
  1: "安宮系列",
  2: "本廠",
  3: "OEM",
};

const extraShareRuleData = reactive({
  id: 0,
  name: "",
  ruleType: 1,
  validFrom: "",
  validTo: "",
  items: [],
});
const fetchDoctorShareRules = async () => {
  try {
    loading.value = true;
    const {
      data: {
        doctor,
        consultPlan,
        specifyServices,
        additonalShareRule,
        regularShareRule,
        extraShareRule,
      },
    } = await doctorApi.getDoctorShareRules(Number(route.params.id));
    Object.assign(doctorInfo, doctor);
    Object.assign(consultPlanData, consultPlan);
    specifyServicesData.value = specifyServices;
    additonalShareRuleData.value = additonalShareRule;
    Object.assign(regularShareRuleData, regularShareRule);

    const extraItems = extraShareRule.items;
    const itemsByType = extraItems.reduce((acc, item) => {
      const type = item.productCate;
      if (!acc[type]) {
        acc[type] = [];
      }
      acc[type].push(item);
      return acc;
    }, {});
    extraShareRule.items = itemsByType;
    Object.assign(extraShareRuleData, extraShareRule);
  } catch (error) {
    console.error("獲取分成規則失敗", error);
  } finally {
    loading.value = false;
  }
};

// 初始化加載
onMounted(async () => {
  customConsultTypes.value = await customConsultTypeStore.fetchOptions();
  // console.log(customConsultTypes);
  fetchDoctorShareRules();
});
</script>

<style scoped></style>
